/**
 * Created by Administrator on 2017/2/12.
 */

var pomelo = require('pomelo');

var systemConfig = require('../../../config/systemConfig.json');
module.exports = {
    hasUser: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        callback(null, { data: gPlayerManger.getOpenid(uid) ? true : false });
    },

    /**
     * 检查是否可以注册成为代理
     * @param query
     * @param callback
     */
    checkUserRegisterAgent: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(null, { data: false });
            return;
        }

        var uid = parseInt(query.uid);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(null, { data: false });
                return;
            }

            if (player.isRobot() || player.getGmLevel()) {
                callback(null, { data: false });
                return;
            }

            callback(null, { data: true });
        });
    },

    queryUser: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            }

            var resp = player.user;
            if (!player.getGmLevel()) {
                callback(null, resp);
                return;
            }
            var condition = { 'Club': uid };
            if (systemConfig["UseType"]["Inviter"]) {
                condition = { 'invite.inviter': uid }
            }

            DB.user.count(condition, function (err, count) {
                resp.clubMemberCount = count;
                callback(null, resp);
            });
        });
    },

    queryUserByName: function (query, callback) {
        if (!query.hasOwnProperty("name") || !query.name || (query.name.length == 0)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var name = query.name;
        var nameExp = new RegExp(name);
        DB.user.find({ 'info.name': nameExp }).limit(50).toArray(function (err, items) {
            callback(null, { 'arr': items });
        });
    },

    setGM: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.role)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var level = parseInt(query.role);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            } else {
                player.setGmLevel(level);
                player.setSelfGroup();
                player.sendUserValueChanged("gm", "level");
                callback(null, { level: player.getGmLevel() });
            }
        });
    },

    setPrivilege: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.privilege)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var privilege = parseInt(query.privilege);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            } else {
                var user = player.user;
                user.privilege = privilege;
                player.markDirty("privilege");
                player.save(true);
                callback(null, { privilege: user.privilege });
            }
        });
    },

    setBlock: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.block)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var block = (parseInt(query.block)) ? 1 : 0;

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            } else {
                var user = player.user;
                user.block = block;
                player.markDirty("block");
                player.save(true);
                callback(null, { block: user.block });
            }
        });
    },

    setControlValue: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.value)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var value = parseInt(query.value);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            } else {
                var user = player.user;
                user.controlValue = value;
                player.markDirty("controlValue");
                player.save(true);
                callback(null, { value: user.controlValue });
            }
        });
    },

    getResource: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            }

            callback(Code.SUCCESS, player.getResource());
        });
    },

    addResource: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.num)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var num = parseInt(query.num);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            }

            player.addResource("card", num, "gmAdd");

            callback(Code.SUCCESS, player.getResource());
        });
    },

    alterResource: function (query, callback) {
        if (isNaN(query.uid) || isNaN(query.num) || !query.hasOwnProperty("type")) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var type = query.type;
        if (["card", "coin", "cash"].indexOf(type) == -1) {
            callback(Code.ARGS_VALUE_WRONG);
            return;
        }

        var uid = parseInt(query.uid);
        var num = parseInt(query.num);

        gPlayerManger.getPlayer(uid, function (player) {
            if (!player) {
                callback(Code.UID_INVALID);
                return;
            }

            player.addResource(type, num, "gmAlter");

            callback(Code.SUCCESS, player.getResource());
        });
    },

    agentPay: function (query, callback) {
        var agent = null;
        var target = null;
        var num = 0;

        async.series([
            function (cb) {
                if (isNaN(query.uid) || isNaN(query.target) || isNaN(query.num)) {
                    cb(Code.ARGS_INVALID);
                    return;
                }
                num = parseInt(query.num);
                if (num < 1) {
                    cb(Code.ARGS_VALUE_WRONG);
                    return;
                }

                cb();
            },
            function (cb) {
                gPlayerManger.getPlayer(parseInt(query.uid), function (p) {
                    if (!p) {
                        cb(Code.UID_INVALID);
                        return;
                    }

                    agent = p;
                    cb();
                });
            },
            function (cb) {
                gPlayerManger.getPlayer(parseInt(query.target), function (p) {
                    if (!p) {
                        cb(Code.UID_INVALID);
                        return;
                    }

                    target = p;
                    cb();
                });
            },
            function (cb) {

                if (agent.getGmLevel() == Def.GM_LEVEL_SUPER) {
                    target.payCard(num);
                } else {
                    if (agent.getResource('card') < num) {
                        cb(Code.LACK_OF_CARD);
                        return;
                    }
                    agent.alterResource('card', -num, "payTo");
                    target.payCard(num);
                }


                DB.pay.save({
                    agent: agent.uid,
                    uid: target.uid,
                    num: num,
                    t: Date.stdFormatedString()
                });
                cb();
            }
        ], function (err) {
            if (err) {
                callback(err);
                return;
            }

            callback(Code.SUCCESS, {
                agent: agent.getResource(),
                target: target.getResource(),
                targetInfo: target.user.info,
            })
        });
    },

    agentPayList: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var day = +query.day || 30;
        var stamp = Date.getStamp() - day * 86400;

        var cursor = DB.pay.find({ 't': { '$gt': stamp }, 'agent': uid }, { '_id': 0 }).limit(500);
        var data = [];
        cursor.each(function (err, item) {
            if (err || cursor.isClosed()) {
                callback(null, { "arr": data });
                return;
            }

            data.push(item);
        });
    },

    userPayList: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var day = +query.day || 30;
        var stamp = Date.getStamp() - day * 86400;

        var cursor = DB.pay.find({ 't': { '$gt': stamp }, 'uid': uid }, { '_id': 0 }).limit(500);
        var data = [];
        cursor.each(function (err, item) {
            if (err || cursor.isClosed()) {
                callback(null, { "arr": data });
                return;
            }

            data.push(item);
        });
    },

    queryResourceLog: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var uid = parseInt(query.uid);
        var startStamp = parseInt(query.startTime) || (new Date()).zeroTime().getStamp();
        var endStamp = parseInt(query.endTime) || Date.getStamp();
        var condition = {
            'uid': uid, 't': {
                '$gt': Date.createFromStamp(startStamp).stdFormatedString(),
                '$lt': Date.createFromStamp(endStamp).stdFormatedString()
            }
        };

        var data = [];
        var cursor = DB.log.find(condition, { '_id': 0 }).sort({ 't': -1 }).limit(1000);
        cursor.each(function (err, item) {
            if (err || cursor.isClosed()) {
                callback(null, { "arr": data });
                return;
            }

            data.push(item);
        });
    },
    queryResourceLogSum: function (query, callback) {
        if (isNaN(query.start) || isNaN(query.end)) {
            callback(Code.ARGS_INVALID);
            return;
        }
        var startTime = Date.createFromStamp(query.start / 1000).stdFormatedString();
        var endTime = Date.createFromStamp(query.end / 1000).stdFormatedString();
        //var condition = { "t": { "$gt":startTime,"$lt":endTime},"r":{"$ne":null}}
        DB.log.group({ "r": true }, { "r": { "$ne": null }, "t": { "$gt": startTime, "$lt": endTime } }, { "card": 0, "cash": 0, "coin": 0 }, function (obj, pre) {
            if (obj["card"]) {
                pre["card"] += obj["card"];
            }
            if (obj["cash"]) {
                pre["cash"] += obj["cash"];
            }
            if (obj["coin"]) {
                pre["coin"] += obj["coin"];
            }
        }, function (err, result) {
            if (err) {
                callback(Code.DB_ERROR);
            }
            callback(null, result);
        });

    },
    queryResourceLogSumDetail: function (query, callback) {
        var startStamp = parseInt(query.start / 1000) || (new Date()).zeroTime().getStamp();
        var endStamp = parseInt(query.end / 1000) || (new Date()).zeroTime().getStamp();
        DB.log.group({ "uid": true }, {
            "r": { "$ne": null }, "card": { "$lt": 0 },
            "t": { "$gt": Date.createFromStamp(startStamp).stdFormatedString(), "$lt": Date.createFromStamp(endStamp).stdFormatedString() }
        },
            { "card": 0 }, function (obj, pre) {

                pre["card"] += obj["card"];


            }, function (err, result) {
                if (err)
                    callback(err)
                callback(null, result)
            });

    },

    getContent: function (query, callback) {
        callback(null, gGlobalManager.getConfig("content", query.name));
    },

    setContent: function (query, callback) {
        gGlobalManager.setConfig("content", query.name, query.content);
        callback();
    },

    setInviterResource: function (query, callback) {
        var resource = {};
        ["card", "cash", "coin"].forEach(function (name) {
            if (query.hasOwnProperty(name) && !isNaN(query[name])) {
                resource[name] = parseInt(query[name]);
            }
        });

        gGlobalManager.setConfig("inviteSetting", "inviterResource", resource);
        callback();
    },

    getInviterResource: function (query, callback) {
        callback(null, gGlobalManager.getConfig("inviteSetting", "inviterResource"));
    },

    setInitResource: function (query, callback) {
        if (isNaN(query.card) || isNaN(query.coin)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        gGlobalManager.setConfig("initResource", "card", parseInt(query.card));
        gGlobalManager.setConfig("initResource", "coin", parseInt(query.coin));
        callback(null, gGlobalManager.getConfig("initResource"));
    },

    getGlobalConfig: function (query, callback) {
        callback(null, gGlobalManager.getConfig(query.name));
    },

    getActivityCreateRoom: function (query, callback) {
        var activity = gGlobalManager.getConfig("activityCreateRoom");
        var resp = {
            startTime: Date.createFromStamp(activity.startTime).stdFormatedString(),
            endTime: Date.createFromStamp(activity.endTime).stdFormatedString(),
            rate: activity.rate,
        };
        callback(null, resp);
    },

    setActivityCreateRoom: function (query, callback) {
        gGlobalManager.setConfig("activityCreateRoom", "startTime", parseInt(query.startTime));
        gGlobalManager.setConfig("activityCreateRoom", "endTime", parseInt(query.endTime));
        gGlobalManager.setConfig("activityCreateRoom", "rate", parseInt(query.rate));
        callback();
    },

    setAdvertisement: function (query, callback) {
        var config = gGlobalManager.getConfig("advertisement");
        if (!config) {
            callback();
            return;
        }

        if (query.hasOwnProperty('show')) {
            gGlobalManager.setConfig("advertisement", "show", parseInt(query.show));
        }

        callback(null, gGlobalManager.getConfig("advertisement"));
    },

    queryNewUserList: function (query, callback) {
        var hour = +query.hour || 24 * 7;
        var stamp = Date.getStamp() - hour * 3600;
        var condition = { 'info.createTime': { '$gt': stamp }, 'robot': { '$exists': false } };

        var cursor = DB.user.find(condition, { 'info': 1, 'status': 1, 'marks': 1 }).sort({ '_id': 1 }).limit(200);
        var data = [];
        cursor.each(function (err, item) {
            if (err || cursor.isClosed()) {
                callback(null, { "arr": data });
                return;
            }

            data.push(item);
        });
    },

    /**
     * 查询玩家列表
     * @param query {start:0, action:-1/1 上一页/下一页}
     * @param callback
     */
    queryUserList: function (query, callback) {
        var resp = { arr: [], page: parseInt(query.page) || 1 };
        async.series([
            function (cb) {
                if (query.start) {
                    cb();
                } else {
                    DB.user.count({ 'robot': { '$exists': false } }, function (err, count) {
                        resp.count = count;
                        cb();
                    });
                }
            },
            function (cb) {
                var condition = { 'robot': { '$exists': false } };
                var sortK = {};
                if (query.start) {
                    var action = parseInt(query.action) || 1;
                    if (action == 1) {
                        condition['_id'] = { '$lt': parseInt(query.start) };
                        sortK['_id'] = -1;
                        resp.page += 1;
                    } else {
                        condition['_id'] = { '$gt': parseInt(query.start) };
                        sortK['_id'] = 1;
                        resp.page -= 1;
                    }
                } else {
                    sortK['_id'] = -1;
                    resp.page = 1;
                }

                DB.user.find(condition).sort(sortK).limit(10).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp.arr = items || [];
                    if (sortK['_id'] == 1) {
                        resp.arr.reverse();
                    }
                    cb();
                });
            }
        ], function (err) {
            callback(null, resp);
        });
    },

    queryUserListByCreateTime: function (query, callback) {
        var startStamp = parseInt(query.startTime) || (new Date()).zeroMonth().getStamp();
        var endStamp = parseInt(query.endTime) || Date.getStamp();
        var condition = {
            'robot': { '$exists': false },

            'info.createTime': {
                '$gt': startStamp,
                '$lt': endStamp
            }
        };

        var resp = { count: 0, arr: [] };

        async.series([
            function (cb) {
                DB.user.count(condition, function (err, count) {
                    resp.count = count;
                    cb();
                });
            },
            function (cb) {
                var cursor = DB.user.find(condition).sort({ '_id': -1 }).limit(1000);
                cursor.each(function (err, item) {
                    if (err || !item) {
                        cb(); return;
                    }

                    resp.arr.push(item);

                    if (cursor.isClosed()) {
                        cb(); return;
                    }
                });
            }
        ], function (err) {
            callback(null, resp);
        });
    },

    /**
     * 查询用户统计
     * @param query
     * @param callback
     */
    queryUserStat: function (query, callback) {
        var resp = {};

        async.series([
            function (cb) {
                DB.user.count({ 'robot': { '$exists': false } }, function (err, count) {
                    resp.total = count;
                    cb();
                });
            },
            function (cb) {
                resp.online = gPlayerManger.getOnlineCount();
                cb();
            }
        ], function (err) {
            callback(null, resp);
        });
    },

    /**
     * 查询玩家房卡日志
     * @param query
     * @param callback
     */
    queryUserCardLog: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var resp = { "arr": [] };
        var uid = parseInt(query.uid);
        var condition = {
            'uid': uid
        };

        var endTime = (query.endTime) ? Date.createFromStamp(parseInt(query.endTime)) : (new Date());
        condition['t'] = { '$lt': endTime.stdFormatedString() };

        if (query.startTime) {
            condition['t']['$gte'] = Date.createFromStamp(parseInt(query.startTime)).stdFormatedString()
        }

        if (isNaN(query.value)) {
            condition["card"] = { '$exists': true }
        } else {
            var value = parseInt(query.value);
            if (value > 0) {
                condition["card"] = { '$gt': 0 }
            } else if (value < 0) {
                condition["card"] = { '$lt': 0 }
            } else {
                condition["card"] = { '$exists': true }
            }
        }

        logger.debug("condition=%j", condition);
        DB.log.find(condition, { '_id': 0 }).sort({ 't': -1 }).limit(1000).toArray(function (err, items) {
            if (err) {
                logger.error("db err = %j", err.stack);
            }

            resp.arr = items || [];
            callback(null, resp);
        });
    },
    /**
     * 查询俱乐部的成员列表
     * @param query
     * @param callback
     */
    queryClubMemberList: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }
        var uid = parseInt(query.uid);

        var resp = { arr: [], page: parseInt(query.page) || 1 };
        async.series([
            function (cb) {
                if (query.start) {
                    cb();
                } else {
                    if (systemConfig["UseType"]["Inviter"]) {
                        DB.user.count({ 'invite.inviter': uid }, function (err, count) {
                            resp.count = count;
                            cb();
                        });
                    } else {
                        DB.user.count({ 'Club': uid }, function (err, count) {
                            resp.count = count;
                            cb();
                        });
                    }
                }
            },
            function (cb) {
                var condition;
                if (systemConfig["UseType"]["Inviter"]) {
                    condition = { 'invite.inviter': uid }
                } else {
                    condition = { 'Club': uid }
                }

                var sortK = {};
                if (query.start) {
                    var action = parseInt(query.action) || 1;
                    if (action == 1) {
                        condition['_id'] = { '$lt': parseInt(query.start) };
                        sortK['_id'] = -1;
                        resp.page += 1;
                    } else {
                        condition['_id'] = { '$gt': parseInt(query.start) };
                        sortK['_id'] = 1;
                        resp.page -= 1;
                    }
                } else {
                    sortK['_id'] = -1;
                    resp.page = 1;
                }

                resp.arr = DB.user.find(condition).sort(sortK).limit(10).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp.arr = items || [];
                    if (sortK['_id'] == 1) {
                        resp.arr.reverse();
                    }
                    cb();
                });
            }
        ], function (err) {
            callback(null, resp);
        });
    },
    /**
     * 查询俱乐部的成员消耗列表
     * @param query
     * @param callback
     */
    queryClubMemberCostList: function (query, callback) {
        if (isNaN(query.uid)) {
            callback(Code.ARGS_INVALID);
            return;
        }
        var startStamp = parseInt(query.start / 1000) || (new Date()).zeroTime().getStamp();
        var endStamp = parseInt(query.end / 1000) || (new Date()).zeroTime().getStamp();

        var uid = parseInt(query.uid);

        var ClubIds = {};
        var CostConditions = [];

        async.series([
            function (cb) {
                DB.user.find({ 'Club': uid }).forEach(function (value) {
                    ClubIds[value["_id"]] = true;
                }, function (err) {
                    if (err)
                        cb(Code.DB_ERROR)
                    cb()
                });
            },
            function (cb) {
                DB.log.group({ "uid": true }, {
                    "r": { "$ne": null }, "card": { "$lt": 0 },
                    "t": { "$gt": Date.createFromStamp(startStamp).stdFormatedString(), "$lt": Date.createFromStamp(endStamp).stdFormatedString() }
                },
                    { "card": 0 }, function (obj, pre) {

                        pre["card"] += obj["card"];


                    }, function (err, result) {
                        if (err)
                            cb(err)
                        CostConditions = result;
                        cb()
                    });
            },
        ], function (err) {
            if (err)
                callback(err)
            var send = CostConditions.filter(function (v) {
                if (ClubIds[v["uid"]]) {
                    return true;
                } else {
                    return false;
                }
            });
            callback(null, send);
        });
    },

    /***
     * 查询群成员列表
     * @param query
     * @param next
     */
    queryMemberOfGroup: function (query, callback) {
        if (isNaN(query.gid)) {
            callback(Code.ARGS_INVALID);
            return;
        }
        var gid = parseInt(query.gid);

        var resp = { arr: [], page: parseInt(query.page) || 1 };
        async.series([
            function (cb) {
                if (query.start) {
                    cb();
                } else {
                    DB.user.count({ 'groups': { $all: [gid] } }, function (err, count) {
                        resp.count = count;
                        cb();
                    });
                }
            },
            function (cb) {
                var condition = { 'groups': { $all: [gid] } };
                var sortK = {};
                if (query.start) {
                    var action = parseInt(query.action) || 1;
                    if (action == 1) {
                        condition['_id'] = { '$lt': parseInt(query.start) };
                        sortK['_id'] = -1;
                        resp.page += 1;
                    } else {
                        condition['_id'] = { '$gt': parseInt(query.start) };
                        sortK['_id'] = 1;
                        resp.page -= 1;
                    }
                } else {
                    sortK['_id'] = -1;
                    resp.page = 1;
                }

                resp.arr = DB.user.find(condition).sort(sortK).limit(10).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp.arr = items || [];
                    if (sortK['_id'] == 1) {
                        resp.arr.reverse();
                    }
                    cb();
                });
            }
        ], function (err) {
            callback(null, resp);
        });
    },

    dayUserStat: function (query, callback) {
        var init = { 'count': 0, 'num1': 0, 'num3': 0, 'num7': 0 };

        var keyf = function (doc) {
            var time = new Date(doc.info.createTime * 1000);
            var day = time.getFullYear() * 10000 + (time.getMonth() + 1) * 100 + time.getDate();
            return { day: day };
        }

        var reduce = function (doc, prev) {
            prev.count += 1;

            var time = new Date(doc.info.createTime * 1000);
            time = Math.floor((+new Date(time.getFullYear(), time.getMonth(), time.getDate())) / 1000);
            if (doc.marks.loginTime > time + 86400) {
                prev.num1++;
            }

            if (doc.marks.loginTime > time + 86400 * 3) {
                prev.num3++;
            }

            if (doc.marks.loginTime > time + 86400 * 7) {
                prev.num7++;
            }
        }

        var condition = { 'robot': { '$exists': false } };
        if (!isNaN(query.startTime)) {
            condition["info.createTime"] = { '$gte': parseInt(query.startTime) }
        }
        if (!isNaN(query.endTime)) {
            if (!condition.hasOwnProperty("info.createTime")) {
                condition["info.createTime"] = {};
            }
            condition["info.createTime"]['$lt'] = parseInt(query.endTime);
        }

        DB.user.group(keyf, condition, init, reduce, function (err, results) {
            if (err || !results) {
                callback();
            }

            callback(null, { "arr": results });
        });
    },

    /***
     * 删除指定群组的指定会员
     * @param query
     * @param callback
     */
    delMemberOfGroup: function (query, callback) {
        if (isNaN(query.gid)) {
            callback({ "result": false });
            return;
        }
        if (isNaN(query.uid)) {
            callback({ "result": false });
            return;
        }

        var gid = query.gid;
        var uid = query.uid;

        gGroupManager.delMemberOfGroup(gid, uid, function (err) {
            if (err) {
                callback({ "result": false });
                return;
            }
            callback({ "result": true });
        });
    },

    queryFeedback: function (query, callback) {
        if (isNaN(query.endTime)) {
            callback(Code.ARGS_INVALID);
            return;
        }

        var endTime = parseInt(query.endTime);
        var condition = { "status": 0 };
        var resp = { arr: [] };

        async.series([
            function (cb) {
                if (endTime) {
                    condition["t"] = { '$lt': Date.createFromStamp(parseInt(endTime)).stdFormatedString() };
                    cb();
                    return;
                }

                DB.feedback.count(condition, function (err, count) {
                    resp.count = count;
                    cb();
                });
            },
            function (cb) {
                var cursor = DB.feedback.find(condition, { '_id': 0 }).sort({ 't': -1 }).limit(20);
                cursor.each(function (err, item) {
                    if (err || cursor.isClosed()) {
                        cb();
                        return;
                    }

                    resp.arr.push(item);
                });
            }
        ], function (err) {
            callback(null, resp);
        });
    },

    paymentDeal: function (query, callback) {
        async.waterfall([
            function (cb) {
                var findCondition = { "_id": query.order_no };
                DB.onlinepay.findOne(findCondition, function (err, result) {
                    if (err) {
                        cb("not find");
                        return;
                    }
                    if (!result.status) {
                        if (query.trade_state == 'success') {
                            var item = result.item;
                            var platform = result.platform;
                            var config = gGlobalManager.getConfig("payment");
                            var rate = config[item];
                            var resource = rate["resource"];
                            var uid = result.uid;

                            var sets = {};
                            sets["status"] = 1;
                            DB.onlinepay.update({ _id: query.order_no }, { '$set': sets }, function (err, result) {
                                if (err) {
                                    cb(Code.DB_ERROR);
                                    return;
                                }
                                gPlayerManger.getPlayer(uid, function (player) {
                                    if (!player) {
                                        cb(Code.UID_INVALID);
                                        return;
                                    }
                                    player.addResource(resource, "payResource");
                                });
                            });
                        } else {
                            cb("not success");
                            return;
                        }
                    } else {
                        cb("already has");
                        return;
                    }
                });

            },
        ], function (err) {
            console.log("DB err" + err);
        });
    },
    /**
     * 查询玩家支付列表
     * @param query {start:0, action:-1/1 上一页/下一页}
     * @param callback
     */
    queryUserPayList: function (query, callback) {
        var resp = { arr: [], page: parseInt(query.page) || 1 };
        async.series([
            function (cb) {
                if (query.start) {
                    cb();
                } else {
                    var condition = {};
                    if (query.uid) {
                        condition = { 'uid': parseInt(query.uid) }
                    }
                    DB.onlinepay.find(condition).count({}, function (err, count) {
                        resp.count = count;
                        cb();
                    });
                }
            },
            function (cb) {
                var condition = {};
                if (query.uid) {
                    condition = { 'uid': parseInt(query.uid) };
                }
                var sortK = { 'time': -1 };
                if (query.start) {
                    var action = parseInt(query.action) || 1;
                    if (action == 1) {
                        condition['time'] = { '$lt': parseInt(query.start) };
                        sortK['time'] = -1;
                        //resp.page += 1;
                    } else {
                        condition['time'] = { '$gt': parseInt(query.start) };
                        sortK['time'] = 1;
                        //resp.page -= 1;
                    }
                } else {
                    sortK['time'] = -1;
                    resp.page = 1;
                }

                DB.onlinepay.find(condition).sort(sortK).limit(10).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp.arr = items || [];
                    if (sortK['time'] == 1) {
                        resp.arr.reverse();
                    }
                    cb();
                });
            }
        ], function (err) {
            //console.log(resp);

            callback(null, resp);
            //console.log(JSON.parse(resp))

        });
    },

    /**
     * 查询玩家支付列表
     * @param query {}
     * @param callback
     */
    queryAllUserPayment: function (query, callback) {
        var resp = [];
        async.series([

            function (cb) {
                var condition = {};
                if (query.uid) {
                    condition = { 'uid': parseInt(query.uid) };
                }
                DB.onlinepay.find(condition).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp = items || [];

                    cb();
                });
            }
        ], function (err) {
            //console.log(resp);
            callback(null, resp);
            //console.log(JSON.parse(resp))
        });
    },
    queryUsersPaySum: function (query, callback) {

        var start = query.start;
        var end = query.end;

        async.waterfall([
            function (cb) {
                var result = []
                var condition = {};
                if (query.uid) {
                    condition = { "invite.inviter": parseInt(query.uid) };
                }
                DB.user.find(condition).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                        cb(err);
                    }
                    result = items || [];
                    cb(null, result);
                });
            },
            function (result, cb) {
                async.map(result, function (item, call) {
                    var condition = { "uid": item["_id"], "time": { "$gt": Date.parse(new Date()) - 604800000, "$lt": Date.parse(new Date()) } }
                    if (start && end) {
                        condition = { "uid": item["_id"], "time": { "$gt": parseInt(start), "$lt": parseInt(end) } }
                    }
                    DB.onlinepay.find(condition).toArray(function (err, items) {
                        if (err) {
                            call(err);
                        }
                        if (items.length == 0) {
                            call(null, 0)
                        } else {

                            var sumMoney = items.reduce(function (a, b) {
                                return { "money": parseFloat(a["money"]) + parseFloat(b["money"]) };
                            }, { "money": 0 });
                            item["sumMoney"] = sumMoney["money"];

                            call(null, item);
                        }
                    });
                }, function (err, results) {
                    if (err) {
                        cb(err);
                    }
                    var res = results.filter(function (v) {
                        return v != 0;
                    });
                    cb(null, res);
                })
            }
        ], function (err, result) {
            //console.log(resp);
            if (err) {
                console.log(err);
            }
            callback(null, result);
            //console.log(JSON.parse(resp))
        });
    },
    queryInvitedUsers: function (query, callback) {
        var resp = [];
        async.series([
            function (cb) {
                var condition = {};
                if (query.uid) {
                    condition = { "invite.inviter": parseInt(query.uid) };
                }
                DB.user.find(condition).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }
                    resp = items || [];
                    resp = items.map(function (v) {
                        return v["_id"];
                    });
                    cb();
                });
            }
        ], function (err) {
            //console.log(resp);
            callback(null, resp);
            //console.log(JSON.parse(resp))
        });
    },
    // 获取大转盘的配置以及配置内容
    getBigWheel: function (query, callback) {
        callback(null, gGlobalManager.getConfig("BigWheel"));
    },

    setBigWheel: function (query, callback) {

        var bigWheel;

        try {
            console.log(query.BigWheel);

            bigWheel = JSON.parse(query.BigWheel);
        } catch (err) {
            console.log("捕捉到例外，开始执行catch块语句 --->");
            console.log("错误名称: " + err.name + " ---> ");
            console.log("错误信息: " + err.message + " ---> ");

            callback(null, { code: Code.ARGS_INVALID });
        }

        console.log(bigWheel);

        gGlobalManager.setConfig("BigWheel", bigWheel);

        callback(null, { code: Code.SUCCESS });
    },
    //获取上传推送内容
    getLastPush: function (query, callback) {
        var isPush = gGlobalManager.getConfig("alyPush");

        if (isPush) {
            var alyPush = require('../../SDK/PUSH').ALYPUSH;
            alyPush.listPushRecords(callback);
        } else {
            callback(null, { code: Code.GAME_TYPE_INVALID });
        }
    },
    //推送消息
    pushToAll: function (query, callback) {
        var pushArgs = {};
        console.log(query);
        var isPush = gGlobalManager.getConfig("alyPush");
        if (isPush) {
            var alyPush = require('../../SDK/PUSH').ALYPUSH;
            ExObject.each(query, function (k, v) {
                if (k != 'act') {
                    pushArgs[k.capWord()] = v;
                }
            });
            console.log(pushArgs);
            alyPush.push(pushArgs, callback);
        } else {
            callback(null, { code: Code.GAME_TYPE_INVALID });
        }
    },
    // 后台根据比赛场流水号获取对应比赛的信息
    getMatchInfoDetail: function (query, callback) {

        // 检查参数
        var matchSN = query.matchSN;
        if (matchSN == null) {
            callback(null, { code: Code.ARGS_INVALID });
            return;
        }

        var resp = {};

        // 从数据库中进行获取
        // 使用find 获取的是数组, 需要进行取下标才能进行操作
        // 使用findOne 获取的是第一个满足该条件的值，因为这里的流水号是唯一的..所以使用findOne就可以了
        async.series([function (cb) {
            DB.match.findOne({ _id: parseInt(matchSN) }, function (err, result) {

                if (err) {
                    callback(err, { code: err });
                    return;
                }

                resp['match'] = result;

                if (!result || result.length < 1) {
                    cb(Code.ARGS_INVALID);
                    return;
                }

                cb();
            });
        }, function (cb) {
            // 还需要获取一下对应的玩家信息
            gMatchManager.getPlayerInfo([resp['match']], callback, resp);
        }], function (err) {
            if (err) {
                callback(err, { code: err });
                return;
            }
        });
    },

    // 获取玩家参加比赛的场次
    getMatchPlayerList: function (query, callback) {

        var resp = { arr: [], page: parseInt(query.page) || 1 };
        var count = query.count || 10;
        async.series([
            function (cb) {
                if (query.start) {
                    cb();
                } else {
                    DB.match.count(function (err, count) {
                        resp.count = count;
                        cb();
                    });
                }
            },
            function (cb) {
                var condition = {};
                var sortK = {};
                if (query.start) {
                    var action = parseInt(query.action) || 1;
                    if (action == 1) {
                        condition["_id"] = { '$lt': parseInt(query.start) };
                        sortK['startTime'] = -1;
                        resp.page += 1;
                    } else {
                        condition["_id"] = { '$gt': parseInt(query.start) };
                        sortK['startTime'] = 1;
                        resp.page -= 1;
                    }
                } else {
                    sortK['startTime'] = -1;
                    resp.page = 1;
                }

                DB.match.find(condition).sort(sortK).limit(count).toArray(function (err, items) {
                    if (err) {
                        logger.error("db err = %j", err.stack);
                    }

                    resp.arr = items || [];
                    if (sortK['startTime'] == 1) {
                        resp.arr.reverse();
                    }

                    if (resp.arr.length < 1) {
                        callback(err, { code: Code.ARGS_INVALID });
                        return;
                    }

                    // 还需要获取一下对应的玩家信息
                    gMatchManager.getPlayerInfo(resp.arr, callback, resp);
                });
            }
        ], function (err) {
            callback(null, resp);
        });

        //// 获取近期的所有比赛列表
        //DB.match.find ().sort({startTime : -1}).limit(1000).toArray(function (err, value) {
        //    if (err) {
        //        callback (err, {code: err});
        //        return;
        //    }
        //
        //    callback (null, {matchs: value});
        //});
        //
        //gMatchManager.getMatchList (page, count, callback);
    },
    // 修改用户领取标记
    updateMatchPlayerMark: function (query, callback) {

        var mark = query.mark;
        var matchSN = query.matchSN;

        if (isNaN(mark) || isNaN(matchSN)) {
            callback(null, { code: Code.ARGS_INVALID });
            return;
        }

        mark = parseInt(mark);
        matchSN = parseInt(matchSN);

        // 获取更新的mark, 以及对应的matchSN
        gMatchManager.updateMatchMark(mark, matchSN, callback);
    },
    changeInviter: function (query, callback) {
        var user = parseInt(query.user);
        var inviter = parseInt(query.inviter);


        if (isNaN(user) || isNaN(inviter)) {
            callback(null, { code: Code.ARGS_INVALID });
            return;
        }

        if (inviter == 0) {
            var userObj = null;

            async.series([
                function (cbin) {
                    gPlayerManger.getPlayer(user, function (p) {
                        if (!p) {
                            cbin(Code.UID_INVALID);
                            return;
                        }
                        userObj = p;
                        cbin(null);
                    });
                }
            ],
                function (err) {
                    if (err) {
                        callback(null, { code: err });
                        return;
                    }
        
                    userObj.setInviterUid(0, 0)
                    if (systemConfig["UseType"]["Inviter"]) {
                        userObj.sendUserValueChanged("invite", "inviter");
                    } else {
                        userObj.sendUserValueChanged("Club");
                    }
                    callback(null,"success");
                })

            return;
        }

        async.waterfall([
            function (cb) {
                async.series([
                    function (cbin) {
                        gPlayerManger.getPlayer(user, function (p) {
                            if (!p) {
                                cbin(Code.UID_INVALID);
                                return;
                            }
                            var userObj = p;
                            cbin(null, userObj);
                        });
                    },
                    function (cbin) {
                        gPlayerManger.getPlayer(inviter, function (p) {
                            if (!p) {
                                cbin(Code.UID_INVALID);
                                return;
                            }

                            var inviterObj = p;
                            cbin(null, inviterObj);
                        });
                    }
                ],
                    function (err, results) {
                        if (err) {
                            cb(err);
                            return;
                        }

                        if (results[0].getGmLevel() == Def.GM_LEVEL_SUPER || results[1].getGmLevel() == 99) {
                            cb(Code.CANNOTBINDGM);
                        } else if (results[1].getGmLevel() == 0) {
                            cb(Code.CANNOTBINDNORMAL);
                        } else {
                            if (results[0].getGmLevel() != 0) {
                                if (results[0].getGmLevel() <= results[1].getGmLevel()) {
                                    cb(Code.CANNOTBINDLOWLEVEL);
                                }
                            } else {
                                cb(null, results[0], results[1]);
                            }
                        }

                    })
            },
            function (userobj, inviterobj, cb) {
                userobj.setInviterUid(inviter, Date.parse(new Date()) / 1000)
                if (systemConfig["UseType"]["Inviter"]) {
                    userobj.sendUserValueChanged("invite", "inviter");
                } else {
                    userobj.sendUserValueChanged("Club");
                }

                cb(null, "success")

            }
        ],
            function (err, result) {
                //console.log(resp);
                if (err) {
                    callback(null,  err );
                    return;
                }
                callback(null, result);
                //console.log(JSON.parse(resp))
            });

    },

    test: function (query, callback) {
        gPlayerManger.getPlayer(112353, function (player) {
            if (!player) {
                callback(null, { data: false });
                return;
            }

            if (player.isRobot() || player.getGmLevel()) {
                callback(null, { data: false });
                return;
            }
            //订单号 时间 金额
            player.feedbackAgency({ "refer": 111101, "t": 1502346965, "money": 10, "order": "wszf1502346965" })

            callback(null, { data: true });
        });
    }
};

